/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.requery.ohos.sqlite.demo.slice;

import io.requery.ohos.database.sqlite.SQLiteDatabase;
import io.requery.ohos.sqlite.demo.ResourceTable;
import io.requery.ohos.sqlite.demo.SqliteContract;
import io.requery.ohos.sqlite.demo.SqliteDbHelper;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.TextField;
import ohos.agp.window.dialog.ToastDialog;
import ohos.data.rdb.ValuesBucket;
import ohos.data.resultset.ResultSet;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

/**
 * DataBaseCRUDSlice
 */
public class DataBaseCRUDSlice extends AbilitySlice {
    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x002A, "DataBaseCRUDSlice");

    Button insert;
    Button readall;
    Button read;
    Button delete;
    Button deletall;
    Button update;
    TextField name;
    TextField age;
    TextField id;
    private SQLiteDatabase mDatabase;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        initDB();
        initLayout();
        initListenersOne();
        initListenersTwo();
    }

    @Override
    public void onStop() {
        super.onStop();
        mDatabase.close();
    }

    private void initDB() {
        mDatabase = SqliteDbHelper.getInstance(getContext()).getWritableDatabase();
    }

    private void showToast(String message) {
        ToastDialog toast = new ToastDialog(getApplicationContext());
        toast.setText(message).show();
    }

    private boolean isEmpty(TextField editText) {
        return editText.getText().trim().length() > 0;
    }

    private void initLayout() {
        insert = (Button) findComponentById(ResourceTable.Id_insert);
        read = (Button) findComponentById(ResourceTable.Id_read);
        readall = (Button) findComponentById(ResourceTable.Id_readall);
        delete = (Button) findComponentById(ResourceTable.Id_delete);
        deletall = (Button) findComponentById(ResourceTable.Id_deleteall);
        update = (Button) findComponentById(ResourceTable.Id_update);
        name = (TextField) findComponentById(ResourceTable.Id_name_txt);
        age = (TextField) findComponentById(ResourceTable.Id_Age_txt);
        id = (TextField) findComponentById(ResourceTable.Id_ID_txt);
    }

    private void initListenersOne() {
        insert.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (isEmpty(name) && isEmpty(age)) {
                    insert(name.getText().trim(), Integer.parseInt(age.getText().trim()));
                } else {
                    showToast("Enter All fields");
                }
            }
        });

        readall.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                    readall();
            }
        });

        update.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (isEmpty(id) && isEmpty(name) && isEmpty(age)) {
                    update(name.getText().trim(), Integer.parseInt(age.getText().trim()),
                            Integer.parseInt(id.getText().trim()));
                } else {
                    showToast("Enter All fields");
                }
            }});

        deletall.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                deleteAll();
            }
        });
    }

    private void initListenersTwo() {
        read.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (isEmpty(id)) {
                    readone(Integer.parseInt(id.getText().trim()));
                } else {
                    showToast("Enter the ID to be searched");
                }
            }});

        delete.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (isEmpty(id)) {
                    delete (Integer.parseInt(id.getText().trim()));
                } else {
                    showToast("Enter the ID to be deleted");
                }
            }});
    }

    private void insert(String name, int age) {
        ValuesBucket values = new ValuesBucket();
        values.putString(SqliteContract.SqlEntry.COLUMN_NAME_EMPNAME, name);
        values.putInteger(SqliteContract.SqlEntry.COLUMN_NAME_AGE, age);
        mDatabase.insert(SqliteContract.SqlEntry.TABLE_NAME, null, values);
        present(this, null);
        showToast("Data Inserted");
    }

    private void readall() {
        ResultSet cursor = mDatabase.rawQuery("select * from emp", null);
        HiLog.debug(LABEL, "Row count " + cursor.getRowCount());
        if (cursor.getRowCount() == 0) {
            showToast("No Data to show");
        }
        cursor.goToFirstRow();
        for (int i = 0; i < cursor.getRowCount(); i++) {
                HiLog.debug(LABEL, "---------------------");
                HiLog.debug(LABEL, "ID: " + cursor.getString(0));
                HiLog.debug(LABEL, "Name: " + cursor.getString(1));
                HiLog.debug(LABEL, "Age: " + cursor.getString(2));
                HiLog.debug(LABEL, "---------------------");
                cursor.goToNextRow();
        }
    }

    private void readone(int id) {
        ResultSet cursor = mDatabase.rawQuery("SELECT * FROM emp WHERE _id = '" + id + "';", null);
        if (cursor.getRowCount() == 0) {
            showToast("No data found");
        }
        if (cursor != null) {
            if (cursor.goToFirstRow()) {
                HiLog.debug(LABEL, "---------------------");
                HiLog.debug(LABEL, "ID: " + cursor.getString(0));
                HiLog.debug(LABEL, "Name: " + cursor.getString(1));
                HiLog.debug(LABEL, "Age: " + cursor.getString(2));
                HiLog.debug(LABEL, "---------------------");
            }
        }
    }

    private void update(String name, int age, int id) {
        String whereClause = "_id=" + id;
        ValuesBucket values = new ValuesBucket();
        values.putString(SqliteContract.SqlEntry.COLUMN_NAME_EMPNAME, name);
        values.putInteger(SqliteContract.SqlEntry.COLUMN_NAME_AGE, age);
        int retVal = mDatabase.update(SqliteContract.SqlEntry.TABLE_NAME, values, whereClause, null);
        present(this, null);
        if (retVal > 0) {
            showToast("Data Updated");
            HiLog.debug(LABEL, "*********************");
            readone(id);
            HiLog.debug(LABEL, "*********************");
        } else {
            showToast("No Such Data found in database");
        }
    }

    private void delete(int id) {
        String whereClause = "_id=" + id;
        int retVal = mDatabase.delete(SqliteContract.SqlEntry.TABLE_NAME, whereClause, null);
            if (retVal > 0) {
                showToast("Data Updated");
                HiLog.debug(LABEL, "*********************");
                readall();
                HiLog.debug(LABEL, "*********************");
            } else {
                showToast("No Such Data found in database");
            }
    }

    private void deleteAll() {
        int retVal = mDatabase.delete(SqliteContract.SqlEntry.TABLE_NAME, "1", null);
        present(this, null);
        if (retVal > 0) {
            showToast("All Data Deleted");
        } else {
            showToast("No Data to be deleted");
        }
    }
}